package com.woniu.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.woniu.util.ConstantTtil;
import com.woniu.util.JwtUtil;
import com.woniu.util.ResponseEnum;
import com.woniu.util.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class JWTinterceptor implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("application/json;charset=UTF-8");

        // 放行 CORS 预检
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }

        // token 读取：优先自定义 header: token；其次 Authorization: Bearer
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            String auth = request.getHeader("Authorization");
            if (auth != null && auth.toLowerCase().startsWith("bearer ")) {
                token = auth.substring(7).trim();
            }
        }

        if (token == null || token.isEmpty()) {
            log.error("TOKEN为空");
            response.getWriter().write(com.alibaba.fastjson.JSONObject.toJSONString(ResponseUtil.get(ResponseEnum.USER_LOGIN_MISS)));
            return false;
        }

        boolean ok;
        try {
            ok = JwtUtil.verifyJwt(token);
            if (!ok) {
                response.getWriter().write(com.alibaba.fastjson.JSONObject.toJSONString(ResponseUtil.get(ResponseEnum.USER_LOGIN_MISS)));
                return false;
            }
        } catch (Exception e) {
            response.getWriter().write(com.alibaba.fastjson.JSONObject.toJSONString(ResponseUtil.get(ResponseEnum.USER_LOGIN_MISS)));
            return false;
        }

        // 验证 token 是否为 Redis 最新值并刷新 TTL
        java.util.Map map = JwtUtil.getPayload(token);
        Object id = map.get("id");
        String cached = stringRedisTemplate.opsForValue().get(com.woniu.util.ConstantTtil.REDIS_JWT_KEY + id);
        if (!token.equals(cached)) {
            log.error("token已过期");
            response.getWriter().write(com.alibaba.fastjson.JSONObject.toJSONString(ResponseUtil.get(ResponseEnum.USER_LOGIN_MISS)));
            return false;
        }
        stringRedisTemplate.opsForValue().set(com.woniu.util.ConstantTtil.REDIS_JWT_KEY + id, token, 60, java.util.concurrent.TimeUnit.HOURS);
        return true;
    }

}
